package com.zhwmall.product.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhwmall.common.entity.product.BrandEntity;
import com.zhwmall.common.utils.R;
import com.zhwmall.product.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 * 品牌
 *
 * @author zhw
 * @email sqzhou@88.com
 * @date 2020-08-18 16:52:35
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){

        IPage<BrandEntity> pageList = brandService.pageList(params);

        return R.ok().put("data", pageList);
    }

    @RequestMapping("/select/{categoryId}")
    public R select(@PathVariable("categoryId") Long categoryId){

        List<BrandEntity> list =  brandService.getBrandByIds(categoryId);

        return R.ok().put("data", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("data", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){

        //判断是否通过效验，没通过返回统一格式
        if (result.hasErrors()){
            Map<String, String> map = CollUtil.newHashMap();

            result.getFieldErrors().forEach(item->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field, message);
            });

            return R.error(400, "校验不合法").put("data", map);
        }

		brandService.save(brand);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BrandEntity brand){
//		brandService.updateById(brand);

		brandService.updateBrandAndCategoryBrandRelation(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
//		brandService.removeByIds(Arrays.asList(brandIds));
        brandService.removeBrandByIds(Arrays.asList(brandIds));
        return R.ok();
    }

}
